package com.financialsharing.controller;

import com.alibaba.fastjson.JSONObject;
import com.financialsharing.dao.CjMapper;
import com.financialsharing.pojo.Operate;
import com.financialsharing.pojo.Users;
import com.financialsharing.pojo.experiment.ExperimentReportVo;
import com.financialsharing.service.CjService;
import com.financialsharing.vo.UserCj;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.financialsharing.common.ServerResponse;
import com.financialsharing.common.UserUtil;
import com.financialsharing.dao.CountDao;
import com.financialsharing.pojo.IlabUser;
import com.financialsharing.pojo.User;
import com.financialsharing.service.JwtLoginService;
import com.financialsharing.service.UserService;
import com.financialsharing.util.*;
import com.financialsharing.util.excel.ExcelUtils;
import com.financialsharing.vo.UserParamsVo;
import com.financialsharing.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private CjService cjService;

    /**
     * 前台用户注册接口
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo, HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("接收到的前台参数为：" + userVo);
        return userService.register(userVo);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }

    /**
     * ilab平台用户登陆 2019年10月11日15:50:32
     */
    @RequestMapping(value = "/ilab/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody IlabUser ilabUser, HttpServletRequest request) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("获取到的ilab参数token为：" + ilabUser.getToken());
        //获取ilab传递过来的token
        String token = ilabUser.getToken();
        try {
            /**
             * 调用ilab接口获取用户信息
             */
            String ilabJson = ilabUtil.getAccessToken(token);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return ServerResponse.createByErrorMsg("token失效，请重新通过ilab进入重做实验");
            }
            String loginName = o.getString("un");
            String username = o.getString("dis");
            //如果数据库存在登陆用户名 则直接返回
            User user = userService.selectUserByLoginName(loginName);
            if (user != null) {
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                System.out.println(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                String token1 = JwtUtil.sign(user, 60L * 1000L * 60L * 24);//token有效期10小时
                /**
                 * todo 统计网站访问次数：登陆成功后统计次数变量count加1
                 */
                int num = countDao.selectCount();
                int count = ++num;
                countDao.updateOne(count);
                return ServerResponse.createBySuccess(token1);
            }
            //不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("ilab平台用户");
            userVo.setProvince("ilab平台");
            userVo.setCity("ilab平台");
            //ilab用户身份
            userVo.setRoleId(5);
            userVo.setPassword(SHA256Util.generateShaPwd("12345"));
            userVo.setEmail("ilab@163.com");
            int resultCount = userService.insertIlabUser(userVo);
            //插入用户数据 给前端返回user的jwt对象
            User u = userService.selectUserByLoginName(userVo.getLoginName());
            //将access_token放入用户对象生成token
            u.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            System.out.println(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            //24小时的token有效期
            String token1 = JwtUtil.sign(u, 60 * 60 * 1000 * 24L);
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
    }

    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo, HttpServletResponse response) {
        if (userVo.getRoleId() == 1 || userVo.getRoleId() == 3) {
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    @RequestMapping(value = "/gitcj", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse gitcj(UserCj UserCj, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        Integer id = u.getId();
        //保存cj到数据库

        String cjname = UserCj.getCjname();
        int cjtime = UserCj.getCjtime();
        double zlgh = UserCj.getZlgh();
        double zzgh = UserCj.getZzgh();
        double fyzj = UserCj.getFyzj();
        double zskh = UserCj.getZskh();
        double zf = UserCj.getZf();
        cjService.save(cjname, cjtime, zlgh, zzgh, fyzj, zskh, zf, id);

        return ServerResponse.createBySuccess();
    }

    @RequestMapping(value = "/gitallcj", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse gitallcj(@RequestBody UserVo userVo, HttpServletResponse response) {
        //保存cj到数据库
        Integer roleId = userVo.getRoleId();
        Integer pageNum = userVo.getPageNum();
        Integer pageSize = userVo.getPageSize();
        if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
            pageSize = 10;
        }


        if (roleId == 1 || roleId == 2) {
            //查看所有的
            PageHelper.startPage(pageNum, pageSize);
            //List<UserCj> findall=cjService.findall();
            List<UserCj> findall2 = cjService.findall2(userVo);
            PageInfo<UserCj> pageInfo = new PageInfo<UserCj>(findall2);
            return ServerResponse.createBySuccess("获取成绩成功", pageInfo);


        }

        if (roleId == 3 || roleId == 4) {
            //查看自己的
            PageHelper.startPage(pageNum, pageSize);
            List<UserCj> findmyself = cjService.findmyself(userVo.getUsername());
            PageInfo<UserCj> pageInfo = new PageInfo<UserCj>(findmyself);
            return ServerResponse.createBySuccess("获取成绩成功", pageInfo);

        }


        return ServerResponse.createBySuccess();
    }

    /**
     * @Author: liuzhaobo
     * @Description: 导出u3d成绩
     * @DateTime: 2022/9/28 0028 14:49
     * @Params:
     * @Return
     */

    @RequestMapping(value = "/importStudent", method = RequestMethod.GET)
    public void importStudent(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        List<UserCj> findall2 = cjService.findall2(userVo);

        excelUtils.cooperationData(request, response, findall2, "财务共享用户实验成绩", UserCj.class);


    }

    @RequestMapping(value = "/delectOne", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse delectOne(@RequestBody UserCj userCj, HttpServletResponse response) {
        int cjid = userCj.getCjid();
        //根据id删除
        cjService.delectOne(cjid);


        return ServerResponse.createBySuccess();
    }


    /**
     * 游客登录
     *
     * @return
     */
    @PostMapping("/tourist")
    @ResponseBody
    public ServerResponse<String> tourist() {
        UserVo loginUser = new UserVo();
        String s = UUID.randomUUID().toString();
        loginUser.setLoginName(s);
        loginUser.setUsername("评审专家");
        loginUser.setRoleId(3);
        loginUser.setSchool("浙江传媒学院");
        loginUser.setProvince("浙江省");
        loginUser.setCity("杭州市");
        loginUser.setPassword("JGL_tourist");
        userService.insertBackUser(loginUser);
        User user = new User();
        //角色id
        user.setRoleId(3);
        //登录名
        user.setLoginName(s);
        //登陆密码
        user.setPassword("JGL_tourist");
        return jwtLoginService.login(user);

    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forget_checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo) {
        return userService.updatePassword(userVo);
    }

    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request) {
        return userService.insertBackUser(userVo);
    }

    /**
     * 根据用户id删除User表数据
     */
    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request) {
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer userId = jsonObject.getInteger("userId");
        logger.info("管理员删除用户,编号为{}", userId);
        return userService.deleteByUserId(userId);
    }

    /**
     * 修改用户信息
     *
     * @param userVo
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody UserVo userVo, HttpServletRequest request) {
        return userService.updateBackendUser(userVo);
    }

    /**
     * 根据用户id查询用户信息
     */
    @RequestMapping(value = "/backend/findById", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id) {
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @GetMapping(value = "/backend/findByParams")
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(UserParamsVo params, HttpServletRequest request, Integer pageNum, Integer pageSize) {
        params.setRoleId(UserUtil.getRoleId(request));
        params.setUserId(UserUtil.getUserId(request));
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 获取模板
     */
    @GetMapping("/getUserTemplate")
    public void getUserTemplate(HttpServletRequest request, HttpServletResponse response) {
        excelUtils.cooperation(request, response, User.class, "上传用户模板");
    }

    /**
     * 获取模板 老师专用
     */
    @GetMapping("/getDemoByStudents")
    public void getUserTemplates(HttpServletRequest request, HttpServletResponse response) {
        excelUtils.cooperation(request, response, Users.class, "上传用户模板");
    }

    /**
     * 上传接口老师用
     */
    @PostMapping("/importByStudent")
    @ResponseBody
    public ServerResponse<Object> importByStudent(MultipartFile file) {
        List<Object> upload = excelUtils.upload(file, Users.class);
        return userService.importUsers2(upload);
    }

    /**
     * 上传接口
     */
    @PostMapping("/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file) {
        List<Object> upload = excelUtils.upload(file, User.class);
        return userService.importUsers(upload);
    }
}